package com.bw.controller.material;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.material.PiMaterial;
import com.bw.entity.user.TbMenu;
import com.bw.resp.ResponseResult;
import com.bw.service.material.IPiMaterialService;
import com.bw.utils.excel.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  原材料前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-15
 */
@RestController
@RequestMapping("material")
public class PiMaterialController {

    @Autowired
    private IPiMaterialService materialService;

    private final Logger logger = LoggerFactory.getLogger(PiMaterialController.class);

    /**
     * @Description:添加原材料
     * @Author: 周明丽
     * @Date: 2020/6/15 19:47
     * @param material:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("save")
    public ResponseResult save(@RequestBody PiMaterial material) {
        logger.info("原材料添加开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            if(null==material.getId()){
                logger.info("原材料添加时对编号进行唯一判断");
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("code",material.getCode());
                List<PiMaterial> piMaterials = materialService.list(queryWrapper);
                if(piMaterials.size()>0){
                    result.setSuccess(false);
                    result.setMessage("保存失败:该原材料已存在");
                    return result;
                }
                materialService.saveOrUpdate(material);
            }else{
                materialService.updateById(material);
            }
            result.setMessage("保存原材料成功");
        } catch (Exception e) {
            logger.error("原材料添加失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("保存原材料失败:" + e.toString());
        }
        logger.info("原材料添加结束");
        return result;
    }

    /**
     * @Description:根据id查询原材料
     * @Author: 周明丽
     * @Date: 2020/6/15 19:48
     * @param id:
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("getById/{id}")
    public ResponseResult getById(@PathVariable("id") Long id) {
        logger.info("原材料回显开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiMaterial material = materialService.getById(id);
            result.setResult(material);
            result.setMessage("查询原材料成功");
        } catch (Exception e) {
            logger.error("原材料回显异常"+ e.toString());
            result.setSuccess(false);
            result.setMessage("查询原材料失败:" + e.toString());
        }
        logger.info("原材料回显结束");
        return result;
    }

    /**
     * @Description:编辑原材料
     * @Author: 周明丽
     * @Date: 2020/6/15 19:54
     * @param material:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("updateById")
    public ResponseResult updateById(@RequestBody PiMaterial material) {
        logger.info("原材料编辑开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiMaterial materials = materialService.getById(material.getId());
            materialService.saveOrUpdate(materials);
            result.setMessage("编辑原材料成功");
        } catch (Exception e) {
            logger.info("编辑原材料失败"+ e.toString());
            result.setSuccess(false);
            result.setMessage("编辑原材料失败:" + e.toString());
        }
        logger.info("原材料修改结束");
        return result;
    }

    /**
     * @Description:原材料列表
     * @Author: 周明丽
     * @Date: 2020/6/15 19:52
     * @param material:
     * @return: com.bw.resp.ResponseResult
     **/
    @PostMapping("list/{currentPage}/{pageSize}")
    public ResponseResult getById(@PathVariable("currentPage") int currentPage,@PathVariable("pageSize") int pageSize,@RequestBody PiMaterial material) {
        logger.info("原材料列表开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {

            PageHelper.startPage(currentPage,pageSize);
            QueryWrapper queryWrapper=new QueryWrapper();
            logger.info("根据条件查询");
            //根据名称模糊
            if(null!=material.getName()){
                queryWrapper.like("name","%"+material.getName()+"%");
            }
            //根据化学元素叫法模糊
            if(null!=material.getChemical()){
                queryWrapper.like("chemical","%"+material.getChemical()+"%");
            }
            List<PiMaterial> materialList =materialService.list(queryWrapper);
            PageInfo pageInfo=new PageInfo(materialList);
            result.setResult(pageInfo);
            result.setMessage("查询原材料成功");
        } catch (Exception e) {
            logger.info("查询原材料失败"+ e.toString());
            result.setSuccess(false);
            result.setMessage("查询原材料失败:" + e.toString());
        }
        logger.info("原材料列表查询结束");
        return result;
    }

    /**
     * @Description:删除原材料
     * @Author: 周明丽
     * @Date: 2020/6/16 9:22
     * @param id:
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("deleteById/{id}")
    public ResponseResult deleteById(@PathVariable("id") Long id) {
        logger.info("原材料删除开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            materialService.removeById(id);
            result.setMessage("删除原材料成功");
        } catch (Exception e) {
            logger.info("删除原材料失败"+ e.toString());
            result.setSuccess(false);
            result.setMessage("删除原材料失败:" + e.toString());
        }
        logger.info("原材料删除结束");
        return result;
    }

    @PostMapping("importExcel")
    public ResponseResult importExcel(MultipartFile file) {
        logger.info("原材料导入开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //1.获取文件后缀
            String ext=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());

            List<Map> mapList = ExcelUtil.readExcel(ext,file.getInputStream());

            System.out.println(mapList);

            String jsonString = JSON.toJSONString(mapList);//map集合转成json字符串
            List<PiMaterial> piMaterial=JSON.parseArray(jsonString,PiMaterial.class);//json字符串转成list 对象集合
            //添加
            materialService.saveBatch(piMaterial);

        } catch (Exception e) {
            logger.error("原材料导入失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("导入原材料失败:" + e.toString());
        }
        logger.info("原材料导入结束");
        return result;
    }

    @GetMapping("excelInput")
    public void excelInput(HttpServletResponse response) throws Exception {

        logger.info("原材料导出开始");

        List<PiMaterial> materialList = materialService.list();
        response.setHeader("Content-type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("原材料数据".getBytes(),"iso-8859-1")+".xls");

        ClassPathResource classPathResource=new ClassPathResource("xls/material.xls");
        InputStream inputStream = classPathResource.getInputStream();
        ExcelUtils.addValue("list",materialList);
        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());

        logger.info("原材料导出结束");
    }
    /**
     * @Description:查询所有的列表
     * @Author: 周明丽
     * @Date: 2020/6/23 10:35

     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("materialList")
    public ResponseResult materialList() {
        logger.info("查询原材料开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            result.setResult(materialService.list());
        } catch (Exception e) {
            logger.error("原材料查询失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("查询原材料失败:" + e.toString());
        }
        logger.info("查询原材料结束");
        return result;
    }



}
